// 
//  MyClass.cs
//  
//  Author:
//       BOUTRY Arnaud <lordphoenix@tuxfamily.org>
// 
//  Copyright (c) 2010 BOUTRY Arnaud as Lordphoenix
// 
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// 

using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Xml;
using Gtk;
using Mono.Unix;

using swmt.swmtProvider;

[assembly:PluginInfo("identi.ca","identica.identica","http://identi.ca/favicon.ico")]

namespace swmt.swmtProvider.identica
{
	public class identica:WebService
	{
		private string _username;
		private string _password;
		private string _configfilename;
		private bool _error;
		private string _errormessage;
		
		private int _lastcount;
		private int _lasttweetid=0;
		private string _responseString="";

		public identica ()
		{
			Catalog.Init("swmtplugins","");
		}
		public override string accountName {
			get {
				return String.Format("{0}@identi.ca",_username);
			}
		}
		public override string Homepage {
			get {
				return String.Format("http://identi.ca/{0}/all",_username);
			}
		}
		public override int LastCount {
			get {
				return _lastcount;
			}
		}
		public override string pluginfile {
			get {
				return String.Format("{0}.dll",Assembly.GetExecutingAssembly().GetName().Name);
			}
		}
		public override string servicename {
			get {
				return "identi.ca";
			}
		}
		public override bool Error {
			get {
				return _error;
			}
		}
		public override string ErrorMessage
		{
			get{
				return _errormessage;
			}
			 
		}
		public override void loadconfig (string filename)
		{
			_configfilename = filename;
			FileStream fichier = File.Open(_configfilename,FileMode.Open);
			StreamReader r = new StreamReader(fichier);
			r.BaseStream.Seek(0,SeekOrigin.Begin);
			string optionstring;
			while(!r.EndOfStream){
				optionstring=r.ReadLine();
				if (!optionstring.StartsWith("#")){
					int cpos = optionstring.IndexOf("=");
					string optionvalue = optionstring.Substring(cpos+1);
					if(optionstring.StartsWith("username"))
						_username= optionvalue;
					if(optionstring.StartsWith("password"))
						_password = optionvalue;
					if(optionstring.StartsWith("lasttweedid"))
						_lasttweetid=Int32.Parse(optionvalue);
				}
			}
			r.Close();
			fichier.Close();
			
		}
		public override void saveconfig (string filename)
		{
			_configfilename = filename;
			FileStream fichier;
			if(File.Exists(_configfilename))
				fichier = File.Open(_configfilename,FileMode.Truncate,FileAccess.Write);
			else
				fichier = File.Open(_configfilename,FileMode.Create);
			StreamWriter w = new StreamWriter(fichier);
			w.BaseStream.Seek(0,SeekOrigin.Begin);
			w.WriteLine("username={0}",_username);
			w.WriteLine("password={0}",_password);
			w.WriteLine("lasttweedid={0}",_lasttweetid);
			w.Flush();
			fichier.Flush();
			w.Close();
			fichier.Close();
		}
		public override void deleteconfigfile ()
		{
			File.Delete(_configfilename);
		}
		public override Gtk.ResponseType Prompt (bool edit)
		{
			IdenticaDialog dlg = new IdenticaDialog();
			if(edit){
				dlg.Username = _username;
				dlg.Password = _password;
			}
			ResponseType result = (ResponseType)dlg.Run();
			if(result==ResponseType.Ok){
				_username = dlg.Username;
				_password = dlg.Password;
			}
			dlg.Hide();
			dlg.Destroy();
			return result;
		}
		public override bool connect ()
		{
			string url;
			_error = false;
			_errormessage ="";
			if (_lasttweetid==0)
				url="http://identi.ca/api/statuses/home_timeline.xml";
			else
				url = string.Format("http://identi.ca/api/statuses/home_timeline.xml&since_id={0}",_lasttweetid);
			try{
				HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
				req.Method="GET";
				req.Credentials = new NetworkCredential(_username,_password);
				WebResponse resp = req.GetResponse();
				StreamReader r = new StreamReader(resp.GetResponseStream());
				_responseString = r.ReadToEnd();
				return true;
			}
			catch(WebException we) {
				if(we.Status == WebExceptionStatus.ProtocolError){
					this._error = true;
					if(((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Unauthorized){
						this._errormessage = Catalog.GetString("Erreur de connexion");
					}
					else 
						_errormessage = we.Message;
				}
				throw;
			}
		}
		public override int GetUnreadCount ()
		{
			XmlDocument response = new XmlDocument();
			response.LoadXml(_responseString);
			XmlNodeList statuslist =response.DocumentElement.GetElementsByTagName("status");
			_lastcount = statuslist.Count;
			if(_lastcount>0){
				XmlElement laststatusnode =(XmlElement)statuslist[0];
				XmlNode idnode = laststatusnode.GetElementsByTagName("id")[0];
				_lasttweetid = Int32.Parse(idnode.InnerText);
			}
			return _lastcount;
		}
	}
}
